package com.heaboy.emaidemo1.util;

import com.heaboy.emaidemo1.config.EmailServersConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class EmailServerSelector {
    // 所有邮箱配置
    private final List<EmailServersConfig.EmailServer> emailServers;
    // 轮询索引
    private final AtomicInteger currentIndex = new AtomicInteger(0);
    @Autowired
    public EmailServerSelector(EmailServersConfig config) {
        this.emailServers = config.getServers();
        if (emailServers == null || emailServers.isEmpty()) {
            throw new RuntimeException("请在application.yml中配置邮箱服务器！");
        }
    }

    //下一个邮箱
    public EmailServersConfig.EmailServer getNextServer() {
        int index = currentIndex.getAndIncrement() % emailServers.size();
        index = Math.abs(index);
        EmailServersConfig.EmailServer server = emailServers.get(index);
        //test
        System.out.println("轮询选中的邮箱：" + server.getUsername() + "，索引：" + index);
        return server;
    }
}